
//promise的实现
function PromiseFn(){
    this.status="pending";
    this.resolveVal=undefined;
    this.rejectVal=undefined;
    this.resolveCallBack=[];
    this.rejectCallBack=[];
    let that=this;
    function resolve(){
        that.resolveVal=arguments[0];
        that.status="resolve";
        if(that.resolveCallBack.length>0){
            that.resolveCallBack.forEach(fn=>fn());
        }
    }
    function reject(){
        that.rejectVal=arguments[0];
        that.status="reject";
        if(that.rejectCallBack.length>0){
            that.rejectCallBack.forEach(fn=>fn());
        }
    }
    try{
        arguments[0](resolve,reject)
    }catch{
        reject();
    }
}

PromiseFn.prototype.then=function(){
    if(this.status==="resolve"){
        arguments[0](this.resolveVal)
    }else if(this.status==="reject"){
        arguments[1](this.rejectVal)
    }else{
        this.resolveCallBack.push(()=>{arguments[0](this.resolveVal)});
        this.rejectCallBack.push(()=>{arguments[1](this.rejectVal)});
    }
}

//同步
// new PromiseFn(function(resolve,reject){
//     console.log("同步执行")
//     resolve("hello PromiseFn")
// }).then(function(res){
//     console.log(`同步resolve执行了 ${res}`)
// },function(res){})

//异步
new PromiseFn(function(resolve,reject){
    let res={};
    console.log("创建Promise")
    setTimeout(()=>{
        res={name:"张三",age:18}
       if(res.name==="张三"){
        resolve(res)
       }else{
           reject("出错了")
       }
    },2000)
}).then(function(res){
    console.log(res)
},function(msg){
    console.log(msg)
})